﻿using HAF.FtpUtility;
using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using SoapNotify.Assistantor;
using SoapNotify.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SoapNotify
{
    public partial class FrmDownPicture : Form
    {
        public FrmDownPicture()
        {
            InitializeComponent();
        }

        #region 消息输出
        private void ShowPopTips(string message)
        {
            MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        int _msgLen = 0;

        private void ShowClear()
        {
            txtMsg.Clear();
        }

        private void ShowMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowMessage), msg);
            }
            else
            {
                if (_msgLen >= 300)
                {
                    txtMsg.Clear();
                    //txtMessages.Text = "";
                    _msgLen = 0;
                }
                LogHelper.WriteDebugLogEx("SysMonitor", msg);

                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();

                _msgLen++;

            }
        }

        #endregion 消息输出

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmDownPicture_Load(object sender, EventArgs e)
        {
            txtSoapUrl.Text = "http://192.168.65.146:80/Writeable/attachment/2024-12-11/651471c0-55f1-43a7-9033-659077ffde4a.jpg";
            txtUpUrl.Text = "ftp://mrspic:mrspicJxm2023panda@172.25.8.180:21/Writeable/attachment/";
        }
        string correlateId = string.Empty;
        string _statSrvApiUrl = "http://192.168.65.146:80/mediamodule/distributefile/updatetaskstatus";

        private void btnSend_Click(object sender, EventArgs e)
        {
            correlateId = txtNum.Text;
            UpdateRemoteTaskStat(correlateId, "处理中", 1);
            
            //第一步下载文件到本地
            string localFileFullPath = GetRemoteFile();
            if (!string.IsNullOrEmpty(localFileFullPath))
            {
                string fileName = Path.GetFileName(txtFilePath.Text);
                string remoteFile = string.Concat(txtUpUrl.Text, txtFilePath.Text.Replace("\\","/"));
                UploadTask(remoteFile, Path.Combine(localFileFullPath, fileName));
            }
        }

        private string GetRemoteFile()
        {
            string localPath = txtSavePath.Text;
            string localFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localPath, DateTime.Now.ToString("yyyyMM/dd").Replace("/", "\\"));
            ShowMessage(string.Format("开始请求{0}到本地{1}", txtSoapUrl.Text, localFullPath));
            if (WebHelper.GetRemoteFile(txtSoapUrl.Text, localFullPath))
            {
                ShowMessage("资源下载成功");
                return localFullPath;
            }
            else
            {
                ShowMessage("资源下载失败");
                UpdateRemoteTaskStat(correlateId, "停止", 0);
                return "";
            }
        }

        private void UploadTask(string remoteUrl, string localAddress)
        {
            try
            {
                var tmpSiteParams = FtpUrlParser.ParseFtpUrl(remoteUrl);
                if (tmpSiteParams != null)
                {
                    ShowMessage(string.Format("开始上传文件{0}", remoteUrl));

                    UpdateRemoteTaskStat(correlateId, "处理中", 2);
                    //启动下载
                    using (FluentFtpHelper ftpClien = new FluentFtpHelper(tmpSiteParams))
                    {
                        ftpClien.LogOutName = correlateId;
                        ftpClien.BufferSize = 1;
                        ftpClien.WriteConsoleMessageEvent = ShowMessage;
                        //ftpClien.UploadEndEvent = TaskEnd;

                        //注意：Path.Combine使用时，后续的地址不能加/或者//
                        //string localPath = Path.Combine(_runConfig.SaveDir, dateStr, cpName);
                        ftpClien.UploadFile(localAddress, tmpSiteParams.FileSets[0].RemoteRootDirectory, correlateId);

                    };
                }
                else
                {
                    UpdateRemoteTaskStat(correlateId, "停止", 0);
                    ShowMessage(string.Format("任务解析失败 {0}", remoteUrl));
                }
            }
            catch (Exception ex)
            {
                UpdateRemoteTaskStat(correlateId, "停止", 0);
                ShowMessage(ex.ToString());
            }
        }

        private void TaskEnd(string tid, bool stat)
        {
            if (stat)
            {
                ShowMessage("本次上传工作完成");
                UpdateRemoteTaskStat(tid, "完成", 100);
            }
            else
            {
                //失败的任务，进度归零
                UpdateRemoteTaskStat(tid, "停止", 0);
            }

            ShowMessage(string.Format("文件上传任务结束 状态为[{0}]", stat));
        }

        private void UpdateRemoteTaskStat(string correlateId, string stat, int percentage)
        {
            try
            {
                TaskReportModel reportData = new TaskReportModel()
                {
                    Id = correlateId,
                    FileName = "picture",
                    OutCode = txtTag.Text,
                    OutName = "",
                    Status = stat,
                    Progress = percentage,
                    CreationTime = DateTime.Now,
                    FinishTime = percentage == 100 ? DateTime.Now : DateTime.MinValue
                };

                string postData = JsonAssistant.Serialize(reportData);
                ShowMessage(string.Format("开始任务执行状态上报{0}", postData));
                string responseStr = WebHelper.PushHttpResponse(_statSrvApiUrl, "POST", "application/json", postData);
                ShowMessage(responseStr);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }

        }

    }
}
